<template>
  <div class="flex rounded-lg">
    <div class="w-[70%]">
      <div class="content">
        <div class="center">
          <div class="title">
            <span>新闻内容：</span> <input class="input" type="text" placeholder="请输入文章摘要或标题">
          </div>
          <div class="title flex">
            <div>
              新闻类型：
            </div>
            <div>
              <el-button v-for="item in newsTypes" :key="item.value" @click="handleClick(item.value)"
                :class="{ 'active': item.value === classReal }">
                {{ item.label }}
              </el-button>
            </div>
          </div>
          <div class="flex title">
            <span>发布时间：</span>
            <div class="select">
              <el-select v-model="timeSort" placeholder="时间排序" style="width: 100px ;height: 30px;"
                @change="handleAddModeChange">
                <el-option label="时间升序" value="0" />
                <el-option label="时间降序" value="1" />
              </el-select>
              <el-select v-model="timeRange" placeholder="时间范围" style="width: 100px ;height: 30px;"
                @change="handleTimeRangeChange">
                <el-option label="全部" value="all" />
                <el-option label="上周" value="lastWeek" />
                <el-option label="自定义" value="custom" />
              </el-select>
              <el-select v-model="addMode" placeholder="添加方式" style="width: 100px ;height: 30px;"
                @change="handleAddModeChange">
                <el-option label="全部" value="-1" />
                <el-option label="手动添加" value="1" />
                <el-option label="系统生成" value="0" />
              </el-select>
              <el-select v-model="publishStatus" placeholder="发布状态" style="width: 100px ;height: 30px;"
                @change="handleAddModeChange">
                <el-option label="全部" value="-1" />
                <el-option label="已发布" value="1" />
                <el-option label="未发布" value="0" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="news-container">
          <ClickToAddPage :selectNews="selectNews" ref="clickToAddPageRef"></ClickToAddPage>
          <DataList :dataList="DataListShow" @updateNews="handleUpdateNews" @add="handleAdd" @remove="handleRemove"
            @click="handleNewsClick" @edit="handleEdit">
          </DataList>
        </div>
        <div>dirty code</div>
      </div>
      <TimePicker v-if="TimePickerShow" @close="handleTimePickerClose" @data-selected="handleDateSelected"></TimePicker>
    </div>
    <div class="w-[30%]">
      <PageToBePublished :DataListShow="DataListShow" :showEmptyMessage="true" ref="releaseRef"></PageToBePublished>
    </div>
  </div>

  <!-- 新闻详情抽屉 - 放在最外层确保能覆盖整个页面 -->
  <PageDetails ref="detailsRef" @drawer2="handleDrawer2"></PageDetails>
</template>

<script setup>
// 阻止属性自动继承，避免多根节点警告
defineOptions({
  inheritAttrs: false
})
import { ref, useTemplateRef, onMounted } from 'vue'
import DataList from '@/page/DataList.vue'
import ClickToAddPage from '@/components/ClickToAddPage.vue'
import TimePicker from '@/components/TimePicker.vue'
import { updateNews } from '@/api/newsApi'
import { ElMessage } from 'element-plus'
import PageToBePublished from '@/page/PageToBePublished.vue'
import PageDetails from '@/page/PageDetails.vue'


// keywords               在 abstractReal 或 newsTitle 模糊匹配
// classReal              分类（1-5），支持多值，如 1,2,3
// addMode                采集方式：0=自动，1=人工
// isPublished            发布状态：0=未发布，1=已发布
// createTimeFrom         创建时间起（YYYY-MM-DD HH:mm:ss）
// createTimeTo           创建时间止（YYYY-MM-DD HH:mm:ss）
// timeRange              与上面二者互斥，格式：from,to
// +sortby                 0=按创建时间降序，1=按创建时间升序


const timeSort = ref('')
const timeRange = ref('')
const addMode = ref('')
const publishStatus = ref('')
const classReal = ref('all')
const DataListShow = ref([])
const TimePickerShow = ref(false)
const selectNews = ref()
const clickToAddPageRef = ref()
const detailsRef = ref()

const dirty = ref()

const handleAddModeChange = (value) => {
  console.log(value)
}

const handleUpdateNews = (newsList) => {
  console.log(newsList)
}

const releaseRef = useTemplateRef('releaseRef')

const newsTypes = [
  { label: '全部(103)', value: '-1' },
  { label: '宏观形式(19)', value: '1' },
  { label: '行业动态(30)', value: '2' },
  { label: '产业链动态(16)', value: '3' },
  { label: '国际能源观察(17)', value: '4' },
  { label: '其他(21)', value: '5' }
]

const handleClick = (type) => {
  console.log(type)
  classReal.value = type
}

const handleNewsClick = (newsData) => {
  console.log(newsData)
  // 只打开PageDetails抽屉并传递新闻数据
  if (detailsRef.value) {
    detailsRef.value.drawer2 = true
    detailsRef.value.newsForm = {
      newsTitle: newsData.title || '',
      newsSource: newsData.siteName || '',
      newsTime: newsData.createTime || '',
      sourceUrl: newsData.newUrl || '',
      abstractReal: newsData.abstractReal || '',
      markContent: newsData.markContent || ''
    }
  }
  // 不再调用ClickToAddPage的handleNewsClick方法，避免打开其他抽屉
}

// 处理编辑按钮点击
const handleEdit = (newsData) => {
  console.log('编辑新闻:', newsData)
  // 调用ClickToAddPage的handleNewsClick方法打开编辑抽屉
  if (clickToAddPageRef.value && clickToAddPageRef.value.handleNewsClick) {
    clickToAddPageRef.value.handleNewsClick(newsData)
  }
}



const handleAdd = async (id) => {

  // 计算当前待发布新闻总数
  const getCurrentNewsCount = () => {
    if (!releaseRef.value || !releaseRef.value.releaseList || !Array.isArray(releaseRef.value.releaseList)) return 0
    return releaseRef.value.releaseList.reduce((total, category) => {
      return total + (category.list && Array.isArray(category.list) ? category.list.length : 0)
    }, 0)
  }

  if (getCurrentNewsCount() >= 10) {
    ElMessage.warning('已达到添加上限')
    return
  }
  const res = await updateNews({ id, isSelect: 1 })
  if (res.code === 200) {
    ElMessage.success('添加成功')
    await releaseRef.value.refresh()
    // 从列表中移除已添加的新闻项
    DataListShow.value = DataListShow.value.map(item => {
      if (item.id === id) {
        item.isSelect = 1
      }
      return item
    })
  }
}

const handleRemove = async (id) => {
  const res = await updateNews({ id, isSelect: 0 })
  console.log(res.code)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    // 刷新待发布列表
    await releaseRef.value.refresh()
    DataListShow.value = DataListShow.value.map(item => {
      if (item.id === id) {
        item.isSelect = 0
      }
      return item
    })
  }
}

const handleTimeRangeChange = (value) => {
  // 添加调试信息，确认事件触发
  console.log('选择的时间范围:', value)
  if (value === 'custom') {
    console.log('显示时间选择器')
    TimePickerShow.value = true
  }
}

// 添加时间选择器关闭方法
const handleTimePickerClose = () => {
  console.log('关闭时间选择器')
  TimePickerShow.value = false
}

// 添加日期选择结果处理方法
const handleDateSelected = (data) => {
  console.log('选择的日期:', data)
}

// 控制抽屉的打开与关闭
const handleDrawer2 = (isOpen) => {
  if (detailsRef.value) {
    detailsRef.value.drawer2 = isOpen
  }
}

onMounted(() => dirty.value = 'dirty')
</script>

<style scoped>
/* 启用content样式，确保页面布局正确 */
.content {
  overflow: auto;
  height: 100vh;
}

.dirty {
  display: none;
}

.news-container {
  padding: 20px 0;
  overflow: auto;
}

.center {
  border-bottom: 1px solid #dcdfe6;
}

.input {
  height: 28px;
  width: 200px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 12px;
  outline: none;
}

.title {
  margin-bottom: 30px;
  margin-right: 10px;
}

.title span {
  margin-right: 10px;
}

.select .el-select {
  margin-right: 10px;
}

.active {
  background-color: #1890ff;
  color: #fff;
}

.news-add {
  height: 40px;
  line-height: 40px;
  border: 1px dashed #ccc;
  border-radius: 5px;
  margin-top: 20px;
}
</style>